"""
scoring.py - Answer checking and score tracking.

Loads answers.txt (format: <question_number> <correct_letter>).
Handles POST /answer, updates session scores, shows a result page,
and provides a /score page.
"""

import os
import urllib.parse
import config

# Load answers on startup
ANSWERS = {}

def load_answers(filename='answers.txt'):
    """Load answers from a text file into a dictionary."""
    global ANSWERS
    ANSWERS = {}
    if not os.path.exists(filename):
        print(f"Warning: '{filename}' not found. No answers loaded.")
        return
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            if not line or ' ' not in line:
                continue
            parts = line.split()
            if len(parts) >= 2:
                try:
                    q_num = int(parts[0])
                    correct = parts[1].upper()
                    ANSWERS[q_num] = correct
                except ValueError:
                    pass

load_answers()


def parse_post_data(handler):
    """Read and parse URL-encoded POST data from the request body."""
    content_length = int(handler.headers.get('Content-Length', 0))
    if content_length == 0:
        return {}
    raw_data = handler.rfile.read(content_length)
    data = urllib.parse.parse_qs(raw_data.decode('utf-8'))
    return {k: v[0] for k, v in data.items()}


def handle_answer(handler):
    """
    Handle POST /answer.
    """
    # Ensure session exists
    if not hasattr(handler, 'session') or handler.session is None:
        handler.send_error(500, 'No session object')
        return

    data = parse_post_data(handler)
    question_str = data.get('question', '').strip()
    choice = data.get('choice', '').strip().upper()

    if not question_str.isdigit() or not choice:
        handler.send_response(302)
        handler.send_header('Location', config.QUESTION_ROUTE_PREFIX)
        handler.end_headers()
        return

    q_num = int(question_str)
    correct_answer = ANSWERS.get(q_num)

    if correct_answer and choice == correct_answer:
        is_correct = True
        handler.session['correct'] = handler.session.get('correct', 0) + 1
    else:
        is_correct = False
        handler.session['incorrect'] = handler.session.get('incorrect', 0) + 1

    correct_display = correct_answer if correct_answer else '?'
    result_text = 'Correct!' if is_correct else f'Incorrect. The correct answer was {correct_display}.'
    score_correct = handler.session.get('correct', 0)
    score_incorrect = handler.session.get('incorrect', 0)

    body_parts = [
        '<!DOCTYPE html>',
        '<html>',
        '<head><title>Answer Result</title></head>',
        '<body>',
        f'<h1>{result_text}</h1>',
        f'<p>Your score: {score_correct} correct, {score_incorrect} incorrect</p>',
        f'<p><a href="{config.QUESTION_ROUTE_PREFIX}/random">Try another random question</a></p>',
        f'<p><a href="{config.QUESTION_ROUTE_PREFIX}">Back to question list</a></p>',
        '</body></html>'
    ]
    body = '\n'.join(body_parts)
    content = body.encode('utf-8')

    handler.send_response(200)
    handler.send_header('Content-Type', 'text/html; charset=utf-8')
    handler.send_header('Content-Length', len(content))
    handler.end_headers()
    handler.wfile.write(content)


def show_score(handler):
    """
    Display a dedicated score page for the logged-in user.
    """
    # Ensure session exists
    if not hasattr(handler, 'session') or handler.session is None:
        handler.send_error(500, 'No session object')
        return

    correct = handler.session.get('correct', 0)
    incorrect = handler.session.get('incorrect', 0)
    total = correct + incorrect

    body_parts = [
        '<!DOCTYPE html>',
        '<html>',
        '<head><title>Your Score</title></head>',
        '<body>',
        '<h1>Your Score</h1>',
        f'<p>Correct: {correct}</p>',
        f'<p>Incorrect: {incorrect}</p>',
    ]
    if total > 0:
        pct = round((correct / total) * 100, 1)
        body_parts.append(f'<p>Percentage: {pct}%</p>')
    else:
        body_parts.append('<p>No questions answered yet.</p>')

    body_parts.append(f'<p><a href="{config.QUESTION_ROUTE_PREFIX}">Question List</a></p>')
    body_parts.append('<p><a href="/">Home</a></p>')
    body_parts.append('<p><a href="/logout">Logout</a></p>')
    body_parts.append('</body></html>')

    body = '\n'.join(body_parts)
    content = body.encode('utf-8')

    handler.send_response(200)
    handler.send_header('Content-Type', 'text/html; charset=utf-8')
    handler.send_header('Content-Length', len(content))
    handler.end_headers()
    handler.wfile.write(content)